package com.linktrip.devicemanager.filter;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.linktrip.devicemanager.entity.UserInfo;
import com.linktrip.devicemanager.util.Constant;

/**
 * 登录认证的拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {
	Logger log = LoggerFactory.getLogger(LoginInterceptor.class);

	/**
	 * Handler执行完成之后调用这个方法
	 */
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exc)
			throws Exception {

	}

	/**
	 * Handler执行之后，ModelAndView返回之前调用这个方法
	 */
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	/**
	 * Handler执行之前调用这个方法
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取请求的URL
		// String url = request.getRequestURI();
		String contexPath = request.getContextPath();
		String url = request.getRequestURI();
		url = url.replace(contexPath, "");

		// 获取Session
		HttpSession session = request.getSession();
		log.info("action:{}", url);
		if (url.equalsIgnoreCase("/redirect/loginPage.lt"))
			return true;
		if (url.startsWith("/api/v1/")) {
			response.setHeader("Access-Control-Allow-Origin", "*");
			return true;
		}

		if (url.startsWith("/service/") && !url.equals("/service/user/checkLogin.lt") || url.startsWith("/redirect")) {
			UserInfo user = (UserInfo) session.getAttribute(Constant.USER_SESSION);
			log.info("user is null ? {}", (user == null));

			if (null == user) {
				// 不符合条件的，跳转到登录界面
				String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
						+ contexPath + "/";
				log.info("contexPath:{}" + contexPath);
				PrintWriter out = response.getWriter();
				out.println("<html>");
				out.println("<script>");
				out.println("window.open ('" + basePath + "','_top')");
				out.println("</script>");
				out.println("</html>");
				return false;
			}
		}
		return true;

	}

}